import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility';
import { Caller } from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window'
import { AppStorageNameConstant } from '../Common/constants/AppStorageNameConstant'
import { WinsleiLogManager } from '@winslei/winsleilog'
import { WinsleiUtilsManager } from '@winslei/winsleiutils'
import { BusinessError } from '@ohos.base';
import settings from '@ohos.settings';

const TAG = 'MainAbility'

export default class MainAbility extends UIAbility {

    caller: Caller | undefined = undefined;

    // 注册caller的release监听
    private regOnRelease(caller: Caller) {
        try {
            caller.on('release', (msg: string) => {
                console.info(`caller onRelease is called ${msg}`);
            })
            console.info('Succeeded in registering on release.');
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error(`Failed to caller register on release. Code is ${code}, message is ${message}`);
        }
    }

    async onButtonGetCaller() {
        try {
            this.caller = await this.context.startAbilityByCall({
                bundleName: 'com.winslei.winsleikit',
                abilityName: 'CalleeAbility'
            });
            if (this.caller === undefined) {
                WinsleiLogManager.hilogIWithTag(TAG, `get caller failed`)
                return;
            }
            WinsleiLogManager.hilogIWithTag(TAG, `get caller success`)
            this.regOnRelease(this.caller)
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            WinsleiLogManager.hilogIWithTag(TAG, `Failed to get caller. Code is ${code}, message is ${message}`)
        }
    }
    
    onCreate(want, launchParam) {
        WinsleiLogManager.hilogIWithTag(TAG, `onCreate want: ${JSON.stringify(want)}, launchParam: ${JSON.stringify(launchParam)}`)

        this.getConfig()

        WinsleiLogManager.abilityName = want['abilityName']

        globalThis.context = this.context
        
        this.onButtonGetCaller()
    }

    // 获取应用配置
    getConfig() {
        // 获取系统字体大小
        let setFontSizeScale = settings.setValueSync(this.context, settings.display.FONT_SCALE, '2');
        let getFontSizeScale = settings.getValueSync(this.context, settings.display.FONT_SCALE, '0');
        WinsleiLogManager.hilogIWithTag(TAG, `getValueSync, fontSizeScale: ${JSON.stringify(getFontSizeScale)}`)

        let fontSizeScale = this.context.config.fontSizeScale
        WinsleiLogManager.hilogIWithTag(TAG, `getConfig, fontSizeScale: ${JSON.stringify(fontSizeScale)}`)
    }

    onDestroy() {
        WinsleiLogManager.hilogIWithTag(TAG, `onDestroy`)
    }

    async onWindowStageCreate(windowStage: Window.WindowStage) {
        WinsleiLogManager.hilogIWithTag(TAG, `onWindowStageCreate`)

        AppStorage.SetOrCreate(AppStorageNameConstant.MAIN_WINDOW_NAME, await windowStage.getMainWindow())

        WinsleiLogManager.hilogIWithTag(TAG, `onWindowStageCreate screenWidth: ${JSON.stringify(WinsleiUtilsManager.display().width())}, screenHeight: ${JSON.stringify(WinsleiUtilsManager.display().height())},`)

        windowStage.loadContent('pages/index', (err, data) => {
            if (err.code) {
                hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR);
                hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
                return;
            }
            hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
            hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
        });
    }

    onWindowStageDestroy() {
        // Main window is destroyed, release UI related resources
        hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
    }

    onForeground() {
        // Ability has brought to foreground
        hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
    }

    onBackground() {
        // Ability has back to background
        hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
    }
}
